package com.superhelper.receiver.service;

import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import com.superhelper.common.Consts;
import com.superhelper.common.domain.baidu.BdPushEntity;
import com.superhelper.common.service.BaiduService;
import com.superhelper.common.utils.JsonHelper;

@Service
public class BdPushValidService {
	private static final Logger log = LoggerFactory
			.getLogger(BdPushValidService.class);
	@Autowired
	private BaiduService bdService;

	public boolean valid(BdPushEntity entity) {
		BeanMap bm = BeanMap.create(entity);
		@SuppressWarnings("unchecked")
		Set<String> st = new TreeSet<String>(bm.keySet());
		StringBuilder sb = new StringBuilder();
		for (String k : st) {
			if ("sign".equalsIgnoreCase(k)) {
				continue;
			}
			sb.append(String.format("%s=%s", k, bm.get(k) + ""));
		}
		String toBeSign = sb.toString();
		String sign = DigestUtils.md5DigestAsHex(toBeSign
				.getBytes(Consts.UTF8_CHARSET));
		log.info("valid toBeSign:{}, mySign:{},comeSign:{}", toBeSign, sign,
				entity.getSign());
		return StringUtils.equalsIgnoreCase(entity.getSign(), sign);
	}

	public String getSign(Map<String, Object> bm) {
		String source = (String) bm.get("source");
		String secret = bdService.getSourceSecret(source);
		bm.put("secret", secret);
		Set<String> st = new TreeSet<String>(bm.keySet());
		StringBuilder sb = new StringBuilder();
		for (String k : st) {
			Object v = bm.get(k);
			String str = null;
			if (v instanceof String || v instanceof Number) {
				str = v + "";
			} else {
				str = JsonHelper.toJson(v);
			}
			sb.append(String.format("%s=%s&", k, str));
		}
		String toBeSign = sb.substring(0, sb.length() - 1).toString();
		String sign = DigestUtils.md5DigestAsHex(toBeSign
				.getBytes(Consts.UTF8_CHARSET));
		log.info("getSign toBeSign:{}, mySign:{}", toBeSign, sign);

		return sign;
	}

	// public static void main(String[] args) {
	// BdOrderPushEntity entity = new BdOrderPushEntity();
	// entity.setAppId(1L);
	// entity.setMessage("message");
	// entity.setRequestId("reqId1");
	// entity.setShopId(2l);
	// entity.setSignature("xxxxxxxx");
	// entity.setTimestamp(3L);
	// entity.setType(4);
	// entity.setUserId(5L);
	// BeanMap bm = BeanMap.create(entity);
	// @SuppressWarnings("unchecked")
	// Set<String> st = new TreeSet<String>(bm.keySet());
	// for (String k : st) {
	// System.out.println(k + ": " + bm.get(k) + "=====" +
	// String.format("%s=%s", k, bm.get(k) + ""));
	//
	// }
	// }
}
